#include "deletewindow.h"
#include <QSqlDatabase>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QSqlQuery>
#include <QSqlError>
#include "qdebug.h"

DeleteWindow::DeleteWindow(QWidget *parent) : QWidget(parent)
{
    ISBN       = new QLabel("ISBN");
    input_ISBN = new QLineEdit();
    search     = new QPushButton("删除");
    shut       = new QPushButton("关闭");
    initLayout();
    connect(search,&QPushButton::clicked,this,&DeleteWindow::deleteItem);
    connect(shut,&QPushButton::clicked,this,&DeleteWindow::close);
}
void DeleteWindow::initLayout()
{
    QWidget* w1     = new QWidget();
    QWidget* w2     = new QWidget();
    QHBoxLayout* h1 = new QHBoxLayout();
    QHBoxLayout* h2 = new QHBoxLayout();
    QVBoxLayout* v1 = new QVBoxLayout();
    h1->addWidget(ISBN);h1->addWidget(input_ISBN);h2->addWidget(search);
    h2->addWidget(search);h2->addWidget(shut);
    w1->setLayout(h1);w2->setLayout(h2);
    v1->addWidget(w1);v1->addWidget(w2);
    this->setLayout(v1);
}
void DeleteWindow::deleteItem()
{
    QString checkISBN=input_ISBN->text();
    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("db1");
    db.setUserName("root");
    db.setPassword("990820");
    if(!db.open())
    {
        qDebug()<<db.lastError().text();
        return;
    }
    QSqlQuery query;
    query.exec("SELECT * FROM BOOK WHERE ISBN = \"" + checkISBN + "\"");
    if(!query.next()) // 结果集为空
    {
        msg = new QLabel("查无此书");msg->setAlignment(Qt::AlignCenter);
        delete this->layout();
        QWidget* w1     = new QWidget();
        QWidget* w2     = new QWidget();
        QHBoxLayout* h1 = new QHBoxLayout();
        QHBoxLayout* h2 = new QHBoxLayout();
        QVBoxLayout* v1 = new QVBoxLayout();
        h1->addWidget(ISBN);h1->addWidget(input_ISBN);
        h2->addWidget(search);h2->addWidget(shut);
        w1->setLayout(h1);w2->setLayout(h2);
        v1->addWidget(w1);v1->addWidget(w2);v1->addWidget(msg);
        this->setLayout(v1);
    }
    else // 结果集不为空
    {
        query.exec("DELETE FROM BOOK WHERE ISBN = \"" + checkISBN + "\"");
        msg = new QLabel("删除完成");msg->setAlignment(Qt::AlignCenter);
        delete this->layout();
        QWidget* w1     = new QWidget();
        QWidget* w2     = new QWidget();
        QHBoxLayout* h1 = new QHBoxLayout();
        QHBoxLayout* h2 = new QHBoxLayout();
        QVBoxLayout* v1 = new QVBoxLayout();
        h1->addWidget(ISBN);h1->addWidget(input_ISBN);
        h2->addWidget(search);h2->addWidget(shut);
        w1->setLayout(h1);w2->setLayout(h2);
        v1->addWidget(w1);v1->addWidget(w2);
        this->setLayout(v1);
    }
    db.close();
}
